package com.android.dongshouzhi.fragment.detail;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dongshouzhi.R;
import com.android.dongshouzhi.activity.DirectBuyGoodsDetailActivity;
import com.android.dongshouzhi.activity.mine.DirectBuyPayOrderActivity1;
import com.android.dongshouzhi.activity.mine.LoginActivity;
import com.android.dongshouzhi.fragment.BaseLazyFragment;
import com.android.dongshouzhi.model.group.DirectBuyGoodsList;
import com.android.dongshouzhi.model.group.DirectBuyGoodsListCallback;
import com.android.dongshouzhi.utils.CommonUtils;
import com.android.dongshouzhi.utils.ConstantsUrl;
import com.android.dongshouzhi.utils.DisplayUtil;
import com.android.dongshouzhi.utils.HttpUtils;
import com.android.dongshouzhi.utils.LoginState;
import com.android.dongshouzhi.utils.ObjectUtils;
import com.android.dongshouzhi.view.recycleview.CustomLoadMoreView;
import com.android.dongshouzhi.view.recycleview.CustomRecycleView;
import com.android.dongshouzhi.view.recycleview.decoration.Fragment_DirectBuy_TabListItemDecoration;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 直购商品列表
 */

public class Fragment_DirectBuy_TabList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;

    private View rootView;
    private AdaptList adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "param1";
    private int position;
    private static final String ARG_PARAM2 = "param2";
    private String bid;
    private int page;
    private ArrayList<DirectBuyGoodsList.ListBean> listdata = new ArrayList<>();
    private View inflate;
    private TextView refresh_textView;
    private static int DATE_NUM = 10;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            position = getArguments().getInt(ARG_PARAM1);
            bid = getArguments().getString(ARG_PARAM2);
        }
    }

    public static Fragment_DirectBuy_TabList newInstance(int position, String bid) {
        Fragment_DirectBuy_TabList fragment = new Fragment_DirectBuy_TabList();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, position);
        args.putString(ARG_PARAM2, bid);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private GridLayoutManager mGridLayoutManager;

    private void initRecycle() {
        adapter = new AdaptList(listdata);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setAdapter(adapter);
        Fragment_DirectBuy_TabListItemDecoration decoration=new Fragment_DirectBuy_TabListItemDecoration(DisplayUtil.dip2px(getActivity(),5));
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ToDetailActivity(adapter.getItem(position).getId());
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.goods_list_item_buy:
                        if (LoginState.getInstance().isLogin(mcontext)) {
                            String detailId = adapter.getItem(position).getId();
                            ToFirmOrder(detailId);
                        } else {
                            startActivity(new Intent(mcontext, LoginActivity.class));
                        }
                        break;
                }
                return false;
            }
        });
    }

    private void ToFirmOrder(String detailId) {
//        Intent intent_address = new Intent(mcontext, BaseObject.class);
//        intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "确认订单");
        Intent intent_address = new Intent(mcontext, DirectBuyPayOrderActivity1.class);
        intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, detailId);
        intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_QTY, 1);
        startActivity(intent_address);
    }

    public void ToDetailActivity(String id) {
        Intent intent = new Intent(mcontext, DirectBuyGoodsDetailActivity.class);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, id);
        startActivity(intent);
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            page = 1;
            GetListData(page);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_directbuy_tablist, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();

        initRecycle();
        return rootView;
    }

    private void ReFreshData() {
        if (mRefreshLayout != null) {

            mRefreshLayout.setColorSchemeResources(R.color.app_title);
            mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page = 1;
                                GetListData(page);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                        mRefreshLayout.setRefreshing(false);
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetListData(page);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page);
    }

    private void GetListData(int page) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        String address = ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_GOODSLISTSDATA;
        HashMap<String, String> map = new HashMap<>();
        map.put("id", bid);
        map.put("page", page + "");
        map.put("size", DATE_NUM + "");
        if (networkConnected) {
            HttpUtils.get(address, map, listCallback);
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    DirectBuyGoodsListCallback listCallback = new DirectBuyGoodsListCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            mRefreshLayout.setRefreshing(false);
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(DirectBuyGoodsList response, int id) {
            mRefreshLayout.setRefreshing(false);
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            if (response.getCode() == 0) {
                List<DirectBuyGoodsList.ListBean> list = response.getList();
                if (list == null) {
                    adapter.loadMoreEnd();
                    if(page == 1){
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                    return;
                }
                if (list.size() == 0 && page == 1) {
                    noData.setVisibility(View.VISIBLE);
                    return;
                }
                if (list != null && list.size() > 0) {
                    if (page == 1) {
                        listdata.clear();
                        listdata.addAll(list);
                        adapter.setNewData(listdata);
                        mRecyclerView.setLayoutManager(mGridLayoutManager);
                        mRecyclerView.setAdapter(adapter);
                        if (list.size() < DATE_NUM) {
                            adapter.loadMoreEnd();
                        }
                    } else {
                        listdata.addAll(list);
                        adapter.addData(list);
                        adapter.loadMoreComplete();
                    }
                } else {
                    if (page == 1) {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                    adapter.loadMoreEnd();
                }
            } else {
                noData.setVisibility(View.VISIBLE);
                noDataTv.setVisibility(View.VISIBLE);
                noDataTv.setText(response.getMsg());
            }
        }
    };

    public class AdaptList extends BaseQuickAdapter<DirectBuyGoodsList.ListBean, BaseViewHolder> {
           int witdh;
        public AdaptList(ArrayList<DirectBuyGoodsList.ListBean> data) {
            super(R.layout.item_list_directbuy, data);
            int margin =  mcontext.getResources().getDimensionPixelOffset(R.dimen.dp_15);
            witdh =   (DisplayUtil.getWindowWidth((Activity) mcontext)-4*margin)/2;

        }


        @Override
        protected void convert(BaseViewHolder holder, final DirectBuyGoodsList.ListBean data) {

            ImageView   imageView =   ((ImageView) holder.getView(R.id.goods_list_item_image));

            ViewGroup.LayoutParams layoutParams =    imageView.getLayoutParams();
           // int witdh =  mcontext.getResources().getDimensionPixelOffset(R.dimen.dp_180);
            layoutParams.width = witdh;
            layoutParams.height = witdh;
            imageView.setLayoutParams(layoutParams);


            ObjectUtils.photo2(mContext, data.getThumb(), imageView);
            holder.setText(R.id.goods_list_item_score, data.getScore() + "积分");
            holder.setText(R.id.goods_list_item_money, "¥" + data.getPrice());
            holder.setText(R.id.goods_list_item_title, data.getName());
            holder.addOnClickListener(R.id.goods_list_item_buy);

            CommonUtils.SetPriceViewHideOrVisible((TextView) holder.getView(R.id.goods_list_item_money),(TextView)holder.getView(R.id.goods_list_item_add),data.getPrice());
        }
    }
}
